// config/api.js
// api config

const CONFIG = require('./config.js');

// 服务器域名
const baseUrl 			= 'https://wc.e-dspen.com:4431';

const requestGet = (url, needSubDomain, accessToken, data) =>{
    return request(url, needSubDomain, 'GET', accessToken, data);
};
const requestPost = (url, needSubDomain, accessToken, data) => {
    return request(url, needSubDomain, 'POST', accessToken, data);
};
const request = (url, needSubDomain, method, accessToken, data) => {
    console.log(url + "接口, 请求参数: " + JSON.stringify(data));
    let _url = baseUrl + (needSubDomain ? '/' + CONFIG.subDomain : '') + url;
    return new Promise((resolve, reject) => {
        wx.request({
            url: _url,
            method: method,
            data: data,
            header: {
                // 'Content-Type': 'application/x-www-form-urlencoded'
                'content-type': 'application/json',
                'accessToken': accessToken
            },
            // dataType: 回包的内容格式，如果设为json，会尝试对返回的数据做一次 JSON解析
            dataType:'json',
            // success: 收到开发者服务成功返回的回调函数，其参数是一个Object
            success(response) {
                console.log(url + "接口, 后端服务器返回信息:" + JSON.stringify(response));
                resolve(response.data)
            },
            // fail: 接口调用失败的回调函数
            fail(error) {
                // console.error("服务器回包信息:" + request);
                reject(error)
            },
            // complete: 接口调用结束的回调函数（调用成功、失败都会执行）
            complete(aaa) {
                // 加载完成
            }
        })
    })
};

/**
 * //TODO ?
 * 小程序的promise没有finally方法，自己扩展下
 */
Promise.prototype.finally = function (callback) {
    var _promise = this.constructor;
    return this.then(
        function (value) {
            _promise.resolve(callback()).then(
                function () {
                    return value;
                }
            );
        },
        function (reason) {
            _promise.resolve(callback()).then(
                function () {
                    throw reason;
                }
            );
        }
    );
};

module.exports = {
    // request,
    requestGet,
    requestPost,
    userDetailByUuid: (accessToken, uuid) => {
        return request('/user/detail/byUuid', false, 'POST', accessToken, {
            "uuid":uuid
        })
    },
    userDetail: (accessToken) => {
        return requestGet('/user/detail', false, accessToken, {
        })
    },
    login: (code) => {
        return request('/auth/login', true, 'post', null, {
            code,
            type: 2
        })
    },
    oauth:(code) => {
        return request("/auth/o/auth", false, "POST", null, {
            "code":code
        })
    },
    loginByWeiXin:(code) => {
        var data = {
            "code":code
        };
        return requestPost("/auth/o/login/byWeiXin", false, null, data)
    }
};
